import React from 'react';
import './index.css';
import { Upload, message } from 'antd';

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

export default class UpCamera extends React.Component{
    //点击上传图片
    constructor(props){
        super();
        this.state = {
            loading: false,
            imageUrl:props.src,
            title:props.title,
            Change:props.Change,
            disabled:props.disabled
        };
    }
    // componentWillReceiveProps(props){
    //   this.setState({
    //     imageUrl:props.src,
    //   });
    // }

    handleChange = info => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          if(this.state.Change!==undefined){
            this.state.Change(info.file);
          }
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, imageUrl =>
            this.setState({
              imageUrl,
              loading: false,
            }),
          );
        }
    };

    render(){
        const { imageUrl } = this.state;

        return (
            <div className="Camera_Upload_Out">
                <Upload
                    disabled={this.state.disabled}
                    accept="image/*"
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                    beforeUpload={beforeUpload}
                    onChange={this.handleChange}
                >
                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : <img alt="" src="./assets/CA/ct_2.png" className="Camera_Upload_Img" />}
                    {imageUrl ? "" : <div className="Camera_Upload_Title">{ this.state.title }</div>}
                </Upload> 
            </div>
        )
    }
}